package znbkBkfx.BKFX_YDZH;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.example.znbk.znbklibrary.base.BaseRecyclerAdapter;
import com.example.znbk.znbklibrary.base.BaseRecyclerViewHolder;
import com.example.znbk.znbklibrary.widget.CustomEditText;
import com.example.znbk.znbklibrary.widget.CustomTextViewToPicture;
import com.example.znbk.znbklibrary.widget.ScaleButton;
import com.lancoo.znbkxx.R;
import com.tt.CoreType;
import com.tt.QType;
import com.tt.SkEgnManager;
import com.tt.listener.OnRecordListener;
import com.tt.widget.AudioRecoderUtils;
import com.tt.widget.JSONTool;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.NumberFormat;
import java.util.List;

import znbkBkfx.GetBkfxJson.BkfxPaperEntity;

public class BkfxYdzhAnswerAdapter_jd extends BaseRecyclerAdapter {

    private Context context;
    private BkfxPaperEntity bkfxPaperEntity;
    private int quesIndex = -1;
    private int childIndex= -1;
    private CallBackAdapterYdzh_jd callBackAdapterYdzh_jd;
    private LayoutInflater inflater;

    public BkfxYdzhAnswerAdapter_jd(Context context, BkfxPaperEntity bkfxPaperEntity, int quesIndex, int childIndex, CallBackAdapterYdzh_jd callBackAdapterYdzh_jd){
        this. context=context;
        this.bkfxPaperEntity = bkfxPaperEntity;
        this.quesIndex = quesIndex;
        this.childIndex = childIndex;
        this.callBackAdapterYdzh_jd = callBackAdapterYdzh_jd;
        inflater=LayoutInflater. from(context);
        getAnswerInfor();
    }

    private int SortIndex = -1;
    private void getAnswerInfor(){
        SortIndex = bkfxPaperEntity.getQuesList().get(quesIndex).getChildList().
                get(childIndex).getSubChildList().get(0).getSubChildItem().get(0).getSortIndex();
    }

    @Override
    public int getItemCount() {
        return 1;
    }

    private TextView mTvChildQuesAsk;
    private TextView mTvChildPageInfor;
    private CustomEditText mCEdtYdjdText;
    private ScaleButton mSBtnClearText;
    private Button mBtnRecord;
    private ScaleButton mSBtnSubmit;

    private LinearLayout mLlUnSubmitAnswerView;
    private LinearLayout mLlSubmitAnswerView;

    private CustomEditText mCEdtItemAnswer;
    private CustomEditText mCEdtStuAnswer;

    @Override
    public void onBindViewHolder(BaseRecyclerViewHolder baseRecyclerViewHolder, final int position) {
        Log.e("onBindViewHolder","====AAAA=============终于进来了====");

        //显示小题信息
        mTvChildQuesAsk = baseRecyclerViewHolder.getView(R.id.tv_childQuesAsk);
        mTvChildPageInfor = baseRecyclerViewHolder.getView(R.id.tv_childPageInfor);
        mTvChildQuesAsk.setVisibility(View.VISIBLE);
        new CustomTextViewToPicture(context,mTvChildQuesAsk,SortIndex+".");
        int ChildListSize = bkfxPaperEntity.getQuesList().get(quesIndex).getChildList().size();
        mTvChildPageInfor.setText(Html.fromHtml(context.getResources().getString(R.string.child_paper_infor,(childIndex+1),ChildListSize)));

        //初始化未作答作答界面View
        mLlUnSubmitAnswerView = baseRecyclerViewHolder.getView(R.id.ll_unSubmitAnswerView);
        //初始化已完成作答界面View
        mLlSubmitAnswerView = baseRecyclerViewHolder.getView(R.id.ll_submitAnswerView);
        //处理相应界面显示
        int SubmitState = bkfxPaperEntity.getPaperAnswer().get(quesIndex).getSubmitState();
        if(SubmitState==2){
            mLlUnSubmitAnswerView.setVisibility(View.GONE);
            mLlSubmitAnswerView.setVisibility(View.VISIBLE);

            mCEdtItemAnswer = baseRecyclerViewHolder.getView(R.id.cedt_itemAnswer);
            mCEdtItemAnswer.setFocusable(false);
            mCEdtStuAnswer = baseRecyclerViewHolder.getView(R.id.cedt_stuAnswer);
            mCEdtStuAnswer.setFocusable(false);


            String ItemAnswer = bkfxPaperEntity.getPaperAnswer().get(quesIndex).getChildList().get(childIndex).
                    getSubChildList().get(0).getSubChildItem().get(0).getItemAnswer();
            String StuAnswer = bkfxPaperEntity.getPaperAnswer().get(quesIndex).getChildList().get(childIndex).
                    getSubChildList().get(0).getSubChildItem().get(0).getStuAnswer();
            double ScoreRate = bkfxPaperEntity.getPaperAnswer().get(quesIndex).getChildList().get(childIndex).
                    getSubChildList().get(0).getSubChildItem().get(0).getScoreRate();


            ItemAnswer = ItemAnswer.replaceAll("\\$","");

            NumberFormat num = NumberFormat.getPercentInstance();
            String mScoreRate = num.format(ScoreRate);
            if(ScoreRate*100<60) {
                mCEdtItemAnswer.setText(Html.fromHtml(context.getResources().
                        getString(R.string.false_zgt_jd_answer_analysis, mScoreRate, ItemAnswer)));
            }else{
                mCEdtItemAnswer.setText(Html.fromHtml(context.getResources().
                        getString(R.string.true_zgt_jd_answer_analysis, mScoreRate, ItemAnswer)));
            }
            if(ItemAnswer.equals(StuAnswer)){
                mCEdtStuAnswer.setText(StuAnswer);
                mCEdtStuAnswer.setTextColor(Color.parseColor("#00b30d"));
            }else{
                if(StuAnswer.equals("")){
                    mCEdtStuAnswer.setText("未作答");
                    mCEdtStuAnswer.setTextColor(Color.parseColor("#ff0000"));
                }else{
                    mCEdtStuAnswer.setText(StuAnswer);
                    mCEdtStuAnswer.setTextColor(Color.parseColor("#ff0000"));
                }
            }

        }else{
            mLlUnSubmitAnswerView.setVisibility(View.VISIBLE);
            mLlSubmitAnswerView.setVisibility(View.GONE);

            //显示阅读简答输入内容
            mCEdtYdjdText = baseRecyclerViewHolder.getView(R.id.cedt_ydjdText);
            mCEdtYdjdText.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {

                }

                @Override
                public void afterTextChanged(Editable s) {
                    String StuAnswer = s.toString().trim();
                    int SubmitState = bkfxPaperEntity.getPaperAnswer().get(quesIndex).getSubmitState();
                    if(SubmitState!=2) {
                        bkfxPaperEntity.getPaperAnswer().get(quesIndex).getChildList().
                                get(childIndex).getSubChildList().get(0).getSubChildItem().get(0).setStuAnswer(StuAnswer);
                    }
                }
            });

            //设置清空按钮功能
            mSBtnClearText = baseRecyclerViewHolder.getView(R.id.sbtn_clearYdjdText);
            mSBtnClearText.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mCEdtYdjdText.setText("");
                    bkfxPaperEntity.getPaperAnswer().get(quesIndex).getChildList().
                            get(childIndex).getSubChildList().get(0).getSubChildItem().get(0).setStuAnswer("");
                }
            });


            //设置语音按钮
            mBtnRecord = baseRecyclerViewHolder.getView(R.id.btn_recordSpeakInput);
            mBtnRecord.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    switch (event.getAction()) {
                        case MotionEvent.ACTION_DOWN:
                            showRecordPopwindow(mBtnRecord);
                            Log.e("mSBtnRecordAnswer", "===============点击了==============" + position);
                            mRecoderUtils = new AudioRecoderUtils();
                            SkEgnManager.getInstance(context).startRecord(mCoreType, "", QType.QTYPE_EMPTY, mOnRecordListener);
                            mRecoderUtils.startRecord();
                            return true;
                        case MotionEvent.ACTION_UP:
                            popWindow.dismiss();
                            mRecoderUtils.stopRecord();
                            return true;
                        case MotionEvent.ACTION_CANCEL:
                            popWindow.dismiss();
                            mRecoderUtils.stopRecord();
                            return true;
                    }
                    return false;
                }
            });


            //显示提交按钮
            mSBtnSubmit  = baseRecyclerViewHolder.getView(R.id.sbtn_submitYdjd);
            mSBtnSubmit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    bkfxPaperEntity.getPaperAnswer().get(quesIndex).setSubmitState(2);
                    callBackAdapterYdzh_jd.callSubmitRefreshView();
                }
            });
        }


    }

    @Override
    public View getHolderView(ViewGroup parent, int position) {
        View view = inflater.inflate(R.layout.bkfx_adapter_item_answer_ydzh_jd,parent, false);
        return view;
    }


    /********************************************************/
    private AudioRecoderUtils mRecoderUtils;
    private String  mCoreType = CoreType.EN_ASR_REC;
    /*
     * 话咪录音操作
     * */
    private List<Boolean> answerResult;
    OnRecordListener mOnRecordListener = new OnRecordListener() {
        @Override
        public void onRecordStart() {
            //开始录制
//            Log.e("==onRecordingAA==","========vad_status==========="+"121212121212");
        }
        @Override
        public void onRecording(int vad_status, int sound_intensity) {
            //录制中
            Log.e("==onRecordingAA==","========vad_status==========="+vad_status);
            Log.e("==onRecordingBB==","=========sound_intensity==========="+sound_intensity);
            showRecordVolumeSize(sound_intensity);
            if(vad_status==2){
                SkEgnManager.getInstance(context).stopRecord();
                mRecoderUtils.stopRecord();
            }
        }
        @Override
        public void onRecordEnd(String result) {
            //录制结束
            try {
                final JSONObject json = new JSONObject(result);
                Log.e("17kouyuAAA", "返回json===>" + result);
                String speakResult = "";
                if(!getResult(result).equals("")) {
                    speakResult = getResult(result);
                }
                Log.e("==AFGAFGG==","========VVVVVVKKKKK》》==========="+speakResult);
                if(!speakResult.equals("")) {
                    String stuAnswer = bkfxPaperEntity.getPaperAnswer().get(quesIndex).getChildList().get(childIndex).getSubChildList().get(0).
                                getSubChildItem().get(0).getStuAnswer();
                        bkfxPaperEntity.getPaperAnswer().get(quesIndex).getChildList().get(childIndex).getSubChildList().get(0).
                                getSubChildItem().get(0).setStuAnswer(stuAnswer+speakResult+".");

                    mCEdtYdjdText.setText(stuAnswer+speakResult+".");
                }

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    };


    private String getResult(String result) {

        String choiceSoundResult = "";
        StringBuilder keyValue = new StringBuilder();
        try{
            JSONObject returnObj = new JSONObject(result);
            JSONObject resultJSONObject = returnObj.getJSONObject("result");
            if(resultJSONObject.has("overall")){
                keyValue.append("总    分: " + resultJSONObject.getString("overall") + "\n");
            }
            Log.e("getResultAAAAA", "====返回json========答案=========>" + resultJSONObject.getString("recognition"));
            choiceSoundResult = resultJSONObject.getString("recognition");

        }catch (Exception e){
            e.printStackTrace();
        }
        keyValue.append("\n");
        keyValue.append(JSONTool.stringToJSON(result));

        return choiceSoundResult;
    }
    /************************************************************/


    public interface CallBackAdapterYdzh_jd {
        void callHideRecordMiView();
        void callRefreshClickAnswer();
        void callSubmitRefreshView();
    }


    private PopupWindow popWindow;
    private ImageView mIvRecordVolume;
    private Drawable drawableVolume;
    private void showRecordPopwindow(Button btnPop) {

        View contentView = LayoutInflater.from(context).inflate(R.layout.popuw_content_top_arrow_layout, null);
        popWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);// 尽量写成数值，要不然左右弹出的位置不好控制
        popWindow.setAnimationStyle(R.style.MyDialogScale);
        popWindow.setBackgroundDrawable(new BitmapDrawable());
        popWindow.setOutsideTouchable(true);

        mIvRecordVolume = contentView.findViewById(R.id.iv_RecordVolume);
        drawableVolume = mIvRecordVolume.getDrawable();

        int popupWidth = popWindow.getWidth();
        int popupHeight = popWindow.getHeight();
        int width = btnPop.getWidth();
        int height = btnPop.getHeight();
        popWindow.showAsDropDown(btnPop, 0, 30-(popupHeight+2*height));
//        popWindow.showAsDropDown(btnPop, (width - popupWidth) / 2, 0);
    }

    private void showRecordVolumeSize(final int volumesize){
        new Thread(new Runnable() {
            @Override
            public void run() {
                Message msg =Message.obtain();
                msg.obj = volumesize;
                msg.what = 1;
                handler.sendMessage(msg);

                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }).start();

    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    int VolumeSize = Integer.valueOf(msg.obj.toString());
                    if(VolumeSize>50){
                        VolumeSize=50;
                    }
                    int LevelSize = VolumeSize*200;
                    drawableVolume.setLevel(LevelSize);
                    break;
            }
        }
    };

}